package com.med.meddataintegrator.jwt.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.med.meddataintegrator.common.pojo.dos.UserDo;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
public class LoginUserInfoVo implements UserDetails {

    //存储用户信息
    private UserDo userDo;

    //存储用户权限集合
    private List<String> permissions;

    //转换格式后的用户权限结合   格式化忽略该字段
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    // 构造器
    public LoginUserInfoVo(UserDo userDo, List<String> permissions) {
        this.userDo = userDo;
        this.permissions = permissions;
    }



    // 获取用户权限集合  此处将权限集合permissions转换成GrantedAuthority集合
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        if (authorities != null){
            return authorities;
        }
        // 将用户角色存储到 该集合中 集合中的元素类型是SimpleGrantedAuthority
        if (permissions != null && permissions.size() > 0){
            authorities =  permissions.stream().map((String premission) -> {
                return new SimpleGrantedAuthority(premission);
            }).collect(Collectors.toList());
            return authorities;
        }

        // 返回空列表
        return Collections.emptyList();
    }

    @Override
    public String getPassword() {
        if (userDo != null) {
            return userDo.getPassword();
        }
        return null;
    }

    @Override
    public String getUsername() {
        if (userDo != null) {
            return userDo.getUsername();
        }
        return null;
    }

    /**
     * 获取用户是否过期 true代表没有过期
     * @return 用户是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 获取用户是否锁定 true代表没有锁定
     * @return 用户是否锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 获取用户密码过期 true代表没有过期
     * @return 用户密码是否过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
